package com.haipumi.ThreadPool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import org.apache.struts2.ServletActionContext;

public class SimpleThread extends Thread {
	private boolean runningFlag;// 是否运行的标记
//	private String argument;
	
	private String root = ServletActionContext.getServletContext().getRealPath(
			"/images/taskPhoto");//文件保存的路径
	private List<File> file;
	private List<String> fileFileName;
	
	
	public void setFile(List<File> file) {
		this.file = file;
	}

	public void setFileFileName(List<String> fileFileName) {
		this.fileFileName = fileFileName;
	}

	// 标志runningFlag 用以激活线程
	public boolean isRunning() {
		return runningFlag;
	}

	public synchronized void setRunning(boolean flag) {
		runningFlag = flag;

		if (flag){
			this.notify();
		}
	}

	// 提示是哪个线程工作
	public SimpleThread(int threadNumber) {
		runningFlag = false;
		// System.out.println("Thread "+threadNumber+" started.");
	}

	public synchronized void run() {
		try {
			while (true) // 无限循环
			{
				if (!runningFlag) // 判断标志位是否为TRUE，如果runningFlag为false ，等待调用
				{
					this.wait();
				} else {
					// 逻辑处理
					for(int i=0;i<file.size();i++){
						try {
							InputStream is = new FileInputStream(file.get(i));
							OutputStream os = new FileOutputStream(new File(root, fileFileName.get(i)));
//							System.out.println("fileFileName: " + fileFileName.get(i));
							// 因为file是存放在临时文件夹的文件，我们可以将其文件名和文件路径打印出来，看和之前的fileFileName是否相同
//							System.out.println("file: " + file.get(i).getName());
//							System.out.println("file: " + file.get(i).getPath());
							byte[] buffer = new byte[500];
							int length = 0;

							while (-1 != (length = is.read(buffer, 0, buffer.length))) {
								os.write(buffer);
							}
							os.close();
							is.close();
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					runningFlag=false;//关闭线程
				}
			}
		} catch (InterruptedException e) {
		}
	}

}
